#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
#include "sendfile.h"
#include <QFileDialog> // 选择文件框

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->ip->setText("127.0.0.1");
    ui->port->setText("8080");
    ui->sendFile->setDisabled(true);

    ui->progressBar->setRange(0,100);
    ui->progressBar->setValue(0);

    // 创建线程对象
    QThread* t = new QThread;
    // 创建任务对象
    SendFile* worker = new SendFile;

    worker->moveToThread(t);

    // 信号和槽的参数类型是一样的: ip + port(且当前信号槽是在worker中执行，已被移动)
    connect(this, &MainWindow::startConnect,worker,&SendFile::ConnectServer);

    // 处理文件发送(信号和槽的参数类型也是一样的)
    connect(this,&MainWindow::sendFile,worker,&SendFile::sendFile);

    // 处理子线程发送的信号
    connect(worker,&SendFile::connectOK,this,[=](){
        ui->connectServer->setText("已成功连接");
        ui->connectServer->setDisabled(true);
    });

    connect(worker,&SendFile::gameOver,this,[=](){
        t->quit();
        t->wait();
        worker->deleteLater();
        t->deleteLater();
    });

    connect(worker, &SendFile::curPercent,ui->progressBar,&QProgressBar::setValue);

    t->start();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_connectServer_clicked()
{
    QString ip = ui->ip->text();
    unsigned short port = ui->port->text().toUShort();
    // 发送自定义信号
    emit startConnect(ip, port);
}

void MainWindow::on_selFile_clicked()
{
    // 弹出选择文件对话框即可
    QString path = QFileDialog::getOpenFileName(); // 得到某个磁盘文件的绝对路径
    if(path.isEmpty())
    {
        ui->sendFile->setDisabled(true);
    }
    else
    {
        ui->filePath->setText(path);
        ui->sendFile->setDisabled(false);
    }
}

void MainWindow::on_sendFile_clicked()
{
    // 发送一个信号告诉子线程让其帮忙发送文件
    emit sendFile(ui->filePath->text());
}
